import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 用户信息接口
 */
export interface UserInfo {
  id: number
  username: string
  nickname: string
  avatar: string
  memberLevel: string
  points: number
  growthValue: number
  maxGrowth: number
}

/**
 * 登录表单接口
 */
export interface LoginForm {
  username: string
  password: string
}

/**
 * 注册表单接口
 */
export interface RegisterForm {
  username: string
  password: string
  confirmPassword: string
}

/**
 * 用户状态管理Store
 */
export const useUserStore = defineStore('user', () => {
  // ==================== 状态 ====================

  /** Token */
  const token = ref<string>('')

  /** 用户信息 */
  const userInfo = ref<UserInfo | null>(null)

  // ==================== 计算属性 ====================

  /** 是否已登录 */
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)

  // ==================== 方法 ====================

  /**
   * 初始化 - 从localStorage恢复登录状态
   */
  const initAuth = () => {
    const savedToken = localStorage.getItem('auth_token')
    const savedUserInfo = localStorage.getItem('user_info')

    if (savedToken && savedUserInfo) {
      token.value = savedToken
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        clearAuth()
      }
    }
  }

  /**
   * 模拟登录API - Mock数据
   */
  const mockLogin = async (loginForm: LoginForm): Promise<{ success: boolean; message: string }> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟账号验证 (简单的演示逻辑)
        if (loginForm.username === 'admin' && loginForm.password === '123456') {
          const mockToken = 'mock_jwt_token_' + Date.now()
          const mockUser: UserInfo = {
            id: 1,
            username: 'admin',
            nickname: '小明同学',
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            memberLevel: '黄金会员',
            points: 1580,
            growthValue: 3260,
            maxGrowth: 5000
          }

          token.value = mockToken
          userInfo.value = mockUser

          // 持久化到localStorage
          localStorage.setItem('auth_token', mockToken)
          localStorage.setItem('user_info', JSON.stringify(mockUser))

          resolve({ success: true, message: '登录成功!' })
        } else if (loginForm.username && loginForm.password) {
          // 其他用户名也允许登录,返回不同等级的用户
          const mockToken = 'mock_jwt_token_' + Date.now()
          const mockUser: UserInfo = {
            id: Math.floor(Math.random() * 1000),
            username: loginForm.username,
            nickname: loginForm.username + '同学',
            avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            memberLevel: '白银会员',
            points: 580,
            growthValue: 860,
            maxGrowth: 2000
          }

          token.value = mockToken
          userInfo.value = mockUser

          localStorage.setItem('auth_token', mockToken)
          localStorage.setItem('user_info', JSON.stringify(mockUser))

          resolve({ success: true, message: '登录成功!' })
        } else {
          resolve({ success: false, message: '用户名或密码不能为空' })
        }
      }, 800) // 模拟网络延迟
    })
  }

  /**
   * 模拟注册API - Mock数据
   */
  const mockRegister = async (registerForm: RegisterForm): Promise<{ success: boolean; message: string }> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (!registerForm.username || !registerForm.password) {
          resolve({ success: false, message: '用户名或密码不能为空' })
          return
        }

        if (registerForm.password !== registerForm.confirmPassword) {
          resolve({ success: false, message: '两次密码输入不一致' })
          return
        }

        if (registerForm.password.length < 6) {
          resolve({ success: false, message: '密码长度不能少于6位' })
          return
        }

        // 模拟注册成功
        resolve({ success: true, message: '注册成功!请登录' })
      }, 800)
    })
  }

  /**
   * 登录
   */
  const login = async (loginForm: LoginForm): Promise<{ success: boolean; message: string }> => {
    return mockLogin(loginForm)
  }

  /**
   * 注册
   */
  const register = async (registerForm: RegisterForm): Promise<{ success: boolean; message: string }> => {
    return mockRegister(registerForm)
  }

  /**
   * 登出
   */
  const logout = () => {
    clearAuth()
  }

  /**
   * 清除认证信息
   */
  const clearAuth = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_info')
  }

  /**
   * 更新用户信息
   */
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...newUserInfo }
      localStorage.setItem('user_info', JSON.stringify(userInfo.value))
    }
  }

  // ==================== 返回 ====================

  return {
    // 状态
    token,
    userInfo,

    // 计算属性
    isLoggedIn,

    // 方法
    initAuth,
    login,
    register,
    logout,
    clearAuth,
    updateUserInfo
  }
})
